<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="商品ID" prop="goodsId">
            <el-input v-model="queryParams.goodsId" placeholder="请输入商品ID" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:gameGoodsInfo:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:gameGoodsInfo:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['mushcoin:gameGoodsInfo:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="gameGoodsInfoList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="ID" align="center" prop="id" sortable="custom" :sort-orders="['ascending', 'descending']"  />
        <el-table-column label="商品ID" align="center" prop="goodsId" sortable="custom" :sort-orders="['ascending', 'descending']"  />
        <el-table-column label="商品类型" align="center" prop="type" sortable="custom" :sort-orders="['ascending', 'descending']" >
          <template #default="scope">
            <dict-tag :options="goods_type_dict" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="商品状态" align="center" prop="status" sortable="custom" :sort-orders="['ascending', 'descending']" >
          <template #default="scope">
            <dict-tag :options="business_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="交易金额展示" align="center" prop="usPrice" />
        <el-table-column label="折扣" align="center" prop="discount" />
        <el-table-column label="交易金额" align="center" prop="price" />

        <el-table-column label="交易数量(Star)" align="center" prop="priceStar" />
        <el-table-column label="商品价值(月份/币/时长)" align="center" prop="goodsValue" />
        <el-table-column label="游戏币代码" align="center" prop="gameCurrencyCode" />

        <el-table-column label="交易币当前价格" align="center" prop="coinRate" />
<!--        <el-table-column label="交易钱包类型" align="center" prop="walletType" />-->
        <el-table-column label="排序" align="center" prop="sort" sortable="custom" :sort-orders="['ascending', 'descending']"  />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['mushcoin:gameGoodsInfo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['mushcoin:gameGoodsInfo:remove']"
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改TG游戏商品对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="gameGoodsInfoFormRef" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品ID" prop="goodsId">
              <el-input v-model="form.goodsId" placeholder="请输入商品ID" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择商品类型">
                <el-option
                  v-for="dict in goods_type_dict"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="商品状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in business_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="交易金额展示" prop="usPrice">
              <el-input v-model="form.usPrice" placeholder="请输入交易金额展示" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="折扣" prop="discount">
              <el-input v-model="form.discount" placeholder="请输入折扣" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="交易金额" prop="price">
              <el-input v-model="form.price" placeholder="请输入交易金额" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="交易数量(Star)" prop="priceStar">
              <el-input v-model="form.priceStar" placeholder="请输入交易数量(Star)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品价值(月份/币/时长)" prop="goodsValue">
              <el-input v-model="form.goodsValue" placeholder="请输入商品价值(月份/币/时长)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="游戏币代码" prop="gameCurrencyCode">
              <el-input v-model="form.gameCurrencyCode" placeholder="请输入游戏币代码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input v-model="form.sort" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listGameGoodsInfo, getGameGoodsInfo, delGameGoodsInfo, addGameGoodsInfo, updateGameGoodsInfo } from '@/api/mushcoin/gameGoodsInfo';
import { GameGoodsInfoVO, GameGoodsInfoQuery, GameGoodsInfoForm } from '@/api/mushcoin/gameGoodsInfo/types';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { business_status, goods_type_dict } = toRefs<any>(proxy?.useDict('business_status', 'goods_type_dict'));

// 表格数据
const gameGoodsInfoList = ref<GameGoodsInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
// 选中数组
const ids = ref<Array<string | number>>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 总条数
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const gameGoodsInfoFormRef = ref<ElFormInstance>();
const uploadRef = ref<ElUploadInstance>();

/*** 导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 1,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/mushcoin/gameGoodsInfo/importData'
});

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: GameGoodsInfoForm = {
  id: undefined,
  goodsId: undefined,
  status: 1,
  title: undefined,
  usPrice: undefined,
  price: undefined,
  sort: undefined,
  type: 1
};
// 默认排序
const defaultSort = ref<any>({
  sorts: [
    { prop: 'type', order: 'ascending' },
    { prop: 'sort', order: 'ascending' }
  ]
});
const data = reactive<PageData<GameGoodsInfoForm, GameGoodsInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    goodsId: undefined,
    oorderByColumn: defaultSort.value.sorts.map((sort) => `${sort.prop} ${sort.order === 'ascending' ? 'ASC' : 'DESC'}`).join(', '),
    params: {}
  },
  rules: {
    goodsId: [{ required: true, message: '商品ID不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '商品状态不能为空', trigger: 'change' }],
    title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
    usPrice: [{ required: true, message: '交易金额展示不能为空', trigger: 'blur' }],
    price: [{ required: true, message: '交易金额不能为空', trigger: 'blur' }],
    goodsValue: [{ required: true, message: '商品价值(月份/币/时长)不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询TG游戏商品列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGameGoodsInfo(queryParams.value);
  gameGoodsInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  gameGoodsInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const handleSortChange = (column: any) => {
  queryParams.value.orderByColumn = column.prop;
  queryParams.value.isAsc = column.order;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GameGoodsInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加TG游戏商品';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: GameGoodsInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getGameGoodsInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改TG游戏商品';
};

/** 提交按钮 */
const submitForm = () => {
  gameGoodsInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGameGoodsInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGameGoodsInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: GameGoodsInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除TG游戏商品编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delGameGoodsInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'mushcoin/gameGoodsInfo/export',
    {
      ...queryParams.value
    },
    `gameGoodsInfo_${new Date().getTime()}.xlsx`
  );
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = 'TG游戏商品导入';
  upload.open = false;
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('mushcoin/gameGoodsInfo/importTemplate', {}, `gameGoodsInfo_template.xlsx`);
};

/**文件上传中处理 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response: any, file: UploadFile) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value?.handleRemove(file);
  ElMessageBox.alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {
    dangerouslyUseHTMLString: true
  });
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}

onMounted(() => {
  getList();
});
</script>
